from flask import g
from app.libs.error_code import RepeatGift, Success
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.models.base import db
from app.models.book import Book
from app.models.gift import Gift

red_gift = Redprint('gift')


@red_gift.route('/gift/<isbn>', methods=['POST'])
@auth.login_required
def add_gift(isbn):
    uid = g.user.uid
    Book.query.filter_by(isbn=isbn).first_or_404()
    gift = Gift.query.filter_by(uid=uid, isbn=isbn).first() # 判断书籍是否重复存在
    if gift:
        raise RepeatGift()
    with db.auto_commit():
        gift = Gift()
        gift.uid = uid
        gift.isbn = isbn
        db.session.add(gift)
    return Success()
